<?php

class AdminController extends BaseController
{

    /**
     * Declares class-based actions.
     */
    public function AdminController()
    {
        ///layout admin
        $this->layout = '//layouts/admin';
    }

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('khan','tudongthanhtoan','LayDuLieuLoDe', 'layketquaxosotudong', 'ThongKeDanhSachThangGameLode'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform
                'actions' => array('test','showmoney','translr','withdraw','index', 'bomb', 'blackorwhite', 'luckytrain', 'news',
                		 'newsdetail', 'users', 'editusers', 'layketquaxoso', 'lode',
                'nhapketqualode','kqxs'),
                'users' => array('admin'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actions()
    {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex()
    {
        // renders the view file 'protected/views/site/index.php'
        // using the default layout 'protected/views/layouts/admin.php'

       // $data['name'] = "HHT";
       // $data['age'] = 23;
       // $data['email'] = "0987120690@yahoo.com";
        $this->render('backend/admin/index', $data);
    }
    
    public function actiontudongthanhtoan()
    {
    	//exit('tam thoi tat');
    	$wdhisotry= new WithdrawForm();
    	$wdhisotry=Withdraw::getWithdrawNotDone();	
    	$url='http://vietlode.com/backend/admin/translr';
    	foreach ($wdhisotry as $m){
    		echo $m['serialno'].'   '.$m['lr_account'].'    '.$m['money'].'<br/>';
    		if ($m['money']==0)
    		{
    			
    		
    		$libertyAPI = new LibertAPIWrapper();
    		 
    		$response =$libertyAPI->sendmoney($m['lr_account'],'usd',$m['money'],'false','service',"","chuyen tien tu vietlode");
    		$withdraw = Withdraw::model()->find('serialno = :serialno', array(':serialno' => $m['serialno']));
    		$withdraw->batch=$response->Batch;
    		echo $response->Date;
    		echo date("Y-m-d H:i:s",strtotime($response->Date." +7 hours"));
    		$withdraw->send_date=date("Y-m-d H:i:s",strtotime($response->Date." +7 hours"));
    		//$withdraw->send_date=date("d-m H:i:s",strtotime("+14 hours"));
    		$withdraw->send_by=date("Y-m-d H:i:s",strtotime($response->Payer." +14 hours"));
    		$withdraw->status=1;
    		if ($withdraw->update())
    			echo $withdraw->batch;
    		else echo 'ko save dc';
    		}
    	
    	}
    	$list_news = Yii::app()->db->createCommand()
    	->select('*')
    	->from('ld_news')
    	->queryAll();
    	// tao actioni gia?
    	$bots=Yii::app()->db->createCommand('select * from ld_user where bot=1')
    	->queryAll();
    	$numofbots=Yii::app()->db->createCommand('select count(*) from ld_user where bot=1')
    	->queryScalar();;
    	$extratime=300;
    	echo 'num of bot la : '.$numofbots.'<br/>';
    	$frequent=0;
    	$gio=intval(date('H',strtotime(" +14 hours")));
  		echo $gio;
  		if ($gio<7)
  			//$frequent=mt_rand(0,1)*3+mt_rand(0,2)*3;
  			$frequent=mt_rand(0,1)*mt_rand(0,1);
  		else if ($gio<16)
  			$frequent=mt_rand(0,1)+mt_rand(0,1)*2;
  		else 
  			$frequent=mt_rand(0,1)*2+mt_rand(0,1)*3;
  		$frequent*=5;
  		echo 'fre : '.$frequent.'<br/>';
    		
    	//var_dump($bots[6]);
    	for ($i=0;$i<$frequent;$i++){
    		$randid=mt_rand(0,$numofbots-1);
    		
    		$extratime -= mt_rand(1,$extratime*0.5);
    		//$extratime =0;// neu chi chay co 1 lan thi lay ngay thoi diem luc chay, ko fai tru di nua
    		echo 'extratime : '.$extratime.'<br/>';
    		$content = date("Y-m-d H:i:s",strtotime("+14 hours -".$extratime." seconds"));
    		$time= $content;
    		$gametype=mt_rand(0,20);
    		if (date("H")%4==0)
    			$gametype=mt_rand(0,20);
    		
    	$now = date('H:i:s d-m-Y');
    	$start = date('05:i:s d-m-Y');
    	$end = date('06:i:s d-m-Y');
    		if($now >= $start && $now < $end)
    		{
    			$gametype=mt_rand(12,20);
    		}
    		
    		$content .= " -- <b>".$bots[$randid]['user_name']."</b>";
    		//echo $randid.'---'.$content.'<br/>';
    		echo $gametype.'<br/>';
    		$status=1;
    		//$gametype=19;
    	    switch ($gametype)
                {
                	
                    case 0:
                    	$betnum=mt_rand(0,50)+mt_rand(0,49);
                    	$betnumstr=(string)$betnum;
                    	if ($betnum>9)
                    	{
                    		$betnumstr='"'.$betnumstr.'"';
                    	}
                    	else
                    		$betnumstr='"0'.$betnumstr.'"';
                    	 
                    	$betmoney=mt_rand(1,80)/10;
                    	$content .= ' vừa mới đánh lô đề ';
                    	$command="INSERT INTO ld_lode(player_id,user_name,choices,
                    	bet,lode_type,play_date)
                    	VALUES(".$bots[$randid]['user_id'].",'".$bots[$randid]['user_name']."',
                    	'[".$betnumstr."]',".$betmoney.",7,'".$time."') ";
                    	echo $command;
                    	Yii::app()->db->createCommand($command)->query();
                    	break;                 	
                    case 1:
                    	$betnum=mt_rand(0,9);
                    	$betnumstr=(string)$betnum;
                    	if ($betnum>9)
                    	{
                    		$betnumstr='"'.$betnumstr.'"';
                    	}
                    	else
                    		$betnumstr='"0'.$betnumstr.'"';
                    	 
                    	$betmoney=mt_rand(1,80)/10;
                    	$content .= ' vừa mới đánh lô đề ';
                    	$command="INSERT INTO ld_lode(player_id,user_name,choices,
                    	bet,lode_type,play_date)
                    	VALUES(".$bots[$randid]['user_id'].",'".$bots[$randid]['user_name']."',
                    	'[".$betnumstr."]',".$betmoney.",5,'".$time."') ";
                    	echo $command;
                    	Yii::app()->db->createCommand($command)->query();
                    	break;                    	
                    case 2:
                    	$betnum=mt_rand(0,9);
                    	$betnumstr=(string)$betnum;
                    	if ($betnum>9)
                    	{
                    		$betnumstr='"'.$betnumstr.'"';
                    	}
                    	else
                    		$betnumstr='"0'.$betnumstr.'"';
                    	 
                    	$betmoney=mt_rand(1,80)/10;
                    	$content .= ' vừa mới đánh lô đề ';
                    	$command="INSERT INTO ld_lode(player_id,user_name,choices,
                    	bet,lode_type,play_date)
                    	VALUES(".$bots[$randid]['user_id'].",'".$bots[$randid]['user_name']."',
                    	'[".$betnumstr."]',".$betmoney.",6,'".$time."') ";
                    	echo $command;
                    	Yii::app()->db->createCommand($command)->query();
                    	break;                    	
                    case 3:
                    case 4:
                    case 5:
                    	
                    case 6:
                    case 7:
                    	$array=array();
                    	for ($num=0;$num<100;$num++)
                    	{
                    		$sql="SELECT days from ld_lokhan where value=".$num;
                    		$daykhan=Yii::app()->db->createcommand($sql)->queryScalar();
                    		for ($i=0;$i<=$daykhan;$i++)
                    			array_push($array,$num);
                    	}
                    	shuffle($array);
                    	print_r($array);
                    	
                    	$betnum=$array[mt_rand(0,count($array)-1)];
                    	echo '<br/> so duoc chon la : '.$betnum.'<br/>';
                    	$betnumstr=(string)$betnum;
                    	if ($betnum>9)
                    	{
                    		$betnumstr='"'.$betnumstr.'"';
                    	}
                    	else
                    		$betnumstr='"0'.$betnumstr.'"';
                    	
                    	$betmoney=mt_rand(1,100)/10;
                    	$content .= ' vừa mới đánh lô đề ';
                    	$command="INSERT INTO ld_lode(player_id,user_name,choices,
                    	bet,lode_type,play_date)
                    	VALUES(".$bots[$randid]['user_id'].",'".$bots[$randid]['user_name']."',
                    	'[".$betnumstr."]',".$betmoney.",1,'".$time."') ";
                    	echo $command;
                    	Yii::app()->db->createCommand($command)->query();
                    	$status=1;
                    	break;  
                    	case 8:
                    	case 9:
                    	case 10:
                    	case 11:
                    		$array=array();
                    		for ($num=0;$num<100;$num++)
                    		{
                    		$sql="SELECT days from ld_lokhan where value=".$num;
                    		$daykhan=Yii::app()->db->createcommand($sql)->queryScalar();
                    		for ($i=0;$i<=$daykhan;$i++)
                    			array_push($array,$num);
                    		}
                    		shuffle($array);
                    		print_r($array);
                    		 
                    		$betnum=$array[mt_rand(0,count($array)-1)];
                    		echo '<br/> so duoc chon la : '.$betnum.'<br/>';
                    		$betnumstr=(string)$betnum;
                    		if ($betnum>9)
                    		{
                    		$betnumstr='"'.$betnumstr.'"';
                    	}
                    	else
                    		$betnumstr='"0'.$betnumstr.'"';
                    		 
                    		$betmoney=mt_rand(1,200)/10;
                    		$content .= ' vừa mới đánh lô đề ';
                    		$command="INSERT INTO ld_lode(player_id,user_name,choices,
                    		bet,lode_type,play_date)
                    		VALUES(".$bots[$randid]['user_id'].",'".$bots[$randid]['user_name']."',
                    		'[".$betnumstr."]',".$betmoney.",1,'".$time."') ";
                    		echo $command;
                    		Yii::app()->db->createCommand($command)->query();
                    		$status=1;
                    		break;                    	     	
                    case 12:
                    	$ranum=mt_rand(0,10);
                    	echo 'gobombanhxac'.$ranum;
                    	$command="SELECT id,user_set_id,money FROM ld_bomb where user_set_id in
                    	(SELECT user_id from ld_user where status=0 and bot=1)
                    	LIMIT ".$ranum." ,1
                    	";
                    	echo $command;
                    	$searchbom=Yii::app()->db->createcommand($command)->queryrow();
                    	if ($searchbom['user_set_id']==null)
                    	{
                    		echo 'ko co bom';
                    		break;
                    	}
                    	$searchuserset=Yii::app()->db->createcommand(
                    			"SELECT user_name FROM ld_user where user_id=".$searchbom['user_set_id']
                    	)->queryrow();
                    	$command="
                    	UPDATE ld_bomb set user_remove_id=
                    	".$bots[$randid]['user_id'].",date_remove='".date("Y-m-d H:i:s")."',status
                    	=-1 where id=".$searchbom['id']."";
                    	$command="DELETE FROM ld_bomb where id=".$searchbom['id'];
                    	Yii::app()->db->createCommand($command)->query();
                    	$content .=" bị nổ banh xác vì bom của <b>".$searchuserset['user_name']."</b> và đánh rơi ".$searchbom['money']."$";
                    	$status=0;
                    	break;
                    case 13:
                    	$ranum=mt_rand(0,10);
                    	echo 'gobomthanhcong'.$ranum;
                    	$command="SELECT id,user_set_id,money FROM ld_bomb where user_set_id in
                    	(SELECT user_id from ld_user where status=0 and bot=1)
                    	LIMIT ".$ranum." ,1
                    	";
                    	echo $command;
                    	
                    	$searchbom=Yii::app()->db->createcommand($command)->queryrow();
                    	if ($searchbom['user_set_id']==null)
                    	{
                    		echo 'ko co bom';
                    		break;
                    	}
                    	$searchuserset=Yii::app()->db->createcommand(
                    			"SELECT user_name FROM ld_user where user_id=".$searchbom['user_set_id']
                    	)->queryrow();
                    	$command="                 	UPDATE ld_bomb set user_remove_id=                    	".$bots[$randid]['user_id'].",date_remove='".date("Y-m-d H:i:s")."',status                    	=1 where id=".$searchbom['id']."";
                    	$command="DELETE FROM ld_bomb where id=".$searchbom['id'];
                    	Yii::app()->db->createCommand($command)->query();
                    	$content .=" đã gỡ thành công bom của <b>".$searchuserset['user_name']."</b> và đã kiếm được ".$searchbom['money']."$";
                    	 
                    	break;
                    case 14:
                    	echo 'lay tien ref';
                    	$content .=" vừa mới thu được <b>".(mt_rand(1,40)/20)."</b> $ tiền giới thiệu user";
                    	break;                	
                    case 15:
                    case 16:
                    	echo 'dat bom';
                    	$money=mt_rand(1,30)/10;
                    	$color=mt_rand(0,1);
                    	if ($color==0)
                    		$color-=1;
                    	$command="INSERT INTO ld_bomb(color,user_set_id,date_set,status,money)
                    	VALUES (".$color.",".$bots[$randid]['user_id'].",'".date("Y-m-d H:i:s")."',0
                    	,".$money.") ";
                    	echo $command.'<br/>';
                    	Yii::app()->db->createCommand($command)->query();
                    	$content .=" vừa mới đặt bom trị giá $".$money;
                    	break;                    	
      	
                    case 17:
                    	$bw=array("0.5","1","2","5","10","20");
                    	$amnt=mt_rand(0,3);
                    	$content .=" vừa mới chơi game black or white và lãi ".$bw[$amnt]*0.9."$";
                    	break;                    	
                    case 18:
                    	$bw=array("0.5","1","2","5","10","20");
                    	$amnt=mt_rand(0,3);
                    	$content .=" vừa mới chơi game black or white và thua ".$bw[$amnt]."$";
                    	$status=0;
                    	break;    
                    case 19:
                    	echo 'aaa';
                    	
                    	$maxamount=Yii::app()->db->createcommand(
                    		"SELECT lr_money from ld_user where user_id=".$bots[$randid]['user_id']
                    			)->queryscalar();
                    	echo 'tien truoc khi rut : '.$maxamount.'<br/>';
                    	if ($maxamount<5){
                    		echo 'ko du 5$, nen ko cho rut';
                    		break;
                    	}
                    	$maxrut=round($maxamount,0,PHP_ROUND_HALF_DOWN);
                    	if ($maxrut>30) 
                    		$maxrut=30;
                    	$fakeamount=mt_rand(1,$maxrut);
                    	$fakeamount/=2;
                    	$content .= ' vừa mới rút '.$fakeamount.'$ khỏi tài khoản';
                    	$command="INSERT INTO ld_withdraw(user_id,send_date,money,currency,status)
                    	VALUES(".$bots[$randid]['user_id'].",'".$time."'
                    	,".$fakeamount.",'LRUSD',1)";
                    	Yii::app()->db->createCommand($command)->query();
                    	$maxamount-=$fakeamount;
                    	echo 'tien con lai la  : '.$maxamount;
                    	$command="UPDATE ld_user set lr_money=".$maxamount." WHERE user_id
                    	=".$bots[$randid]['user_id'];
                    	Yii::app()->db->createcommand($command)->query();
                    	
                    	$total_money = Yii::app()->db->createcommand
                    		("SELECT total_money from ld_total_money")->queryscalar();
                    	$total_money-=$fakeamount;
                    	$command="UPDATE ld_total_money set total_money=".$total_money;
                    	Yii::app()->db->createcommand($command)->query();
                    	
    	
                    	break;
                    case 20:    
                    	                		 
                   		$fakeamount=mt_rand(1,30);
                    	$fakeamount/=2;
                    	$content .=' vừa mới nạp '.$fakeamount.'$ vào tài khoản';
                    	$command="INSERT INTO ld_deposit_history(user_id,deposit_date,lr_amount,lr_currency)
                    	VALUES(".$bots[$randid]['user_id'].",".$time."
                    	,".$fakeamount.",LRUSD)";
                    	//	echo $command.'<br/>';
                    	Yii::app()->db->createCommand("INSERT INTO ld_deposit_history(user_id,deposit_date,lr_amount,lr_currency)
                    			VALUES(".$bots[$randid]['user_id'].",'".$time."'
                    			,".$fakeamount.",'LRUSD')")->query();
                    	$moneybefore=Yii::app()->db->createcommand(
                    			"SELECT lr_money from ld_user where user_id=".$bots[$randid]['user_id']
                    	)->queryscalar();
                    	echo 'tien truoc khi nap : '.$moneybefore;
		               	$moneybefore+=$fakeamount; 
		               	echo '<br/>tien sau khi nap : '.$moneybefore;
                    	$command="UPDATE ld_user set lr_money=".$moneybefore." WHERE user_id
                    	=".$bots[$randid]['user_id'];
                    	Yii::app()->db->createcommand($command)->query();
                    	$total_money = Yii::app()->db->createcommand
                    	("SELECT total_money from ld_total_money")->queryscalar();
                    	$total_money+=$fakeamount;
                    	$command="UPDATE ld_total_money set total_money=".$total_money;
                    	Yii::app()->db->createcommand($command)->query();                    	
                    	break;                    	                	
                }
                $log = array();
                $log['content'] = $content;
                $log['status'] = $status;
                if (strlen($content)>43)
                Yii::app()->db->createCommand()->insert('ld_play_logs', $log);                
    		echo $content.'<br/>';
    	}
    	
    	// delete logs
    	
    	$keyid=Yii::app()->db->createCommand
    	('select id from ld_play_logs order by id desc limit 80,1')->queryScalar();
    	echo 'aaaaaaaaaaaaaaaa'.$keyid;
    	$delete=Yii::app()->db->createCommand('delete from ld_play_logs where id<'.$keyid)
    	->query();
//    	$delete=Yii::app()->db->createCommand
  //  	('delete from ld_play_logs where id<'.$keyid['id'])->query();
    	
    }
    
    public function actionkqxs(){
    	$this->render('backend/admin/kqxs');
    	
    }

    public function actionLogout()
    {
        $_SESSION['isdangnhap'] = false;
        $this->redirect(Yii::app()->request->baseUrl.'/backend/admin/login');
    }

    public function actionLogin()
    {
        // renders the view file 'protected/views/site/index.php'
        // using the default layout 'protected/views/layouts/admin.php'
        $data = array();
        $user = 'admin';
        $pass = 'admin';
        if (isset($_POST['btn_login']))
        {
            $g_user = $_POST['username'];
            $g_pass = $_POST['password'];
            if ($g_user == $user && $g_pass == $pass)
            {
                //dang nhap thanh cong
                Yii::app()->session->open();
                Yii::app()->session['isdangnhap'] = true;
                $_SESSION['isdangnhap'] = true;
                $this->redirect(Yii::app()->request->baseUrl.'/backend/admin');
            }
            else
            {
                $data['error'] = '<span style="color:red;font-weight:bold">Nháº­p láº¡i chÃ­nh xÃ¡c username vÃ   password!</span>';
            }
        }
        $this->layout = 'n';
        $this->render('backend/admin/login', $data);
    }
    
    public function actionshowmoney()
    {
    	$libertyAPI = new LibertAPIWrapper();
    	$response = $libertyAPI->showmoney('usd');
    	//$response[0]='5.67';
    	echo '<b><i>Số tiền chúng tôi còn lại trong tài khoản Liberty : '.$response[0].'</b></i>';
    }
    
    public function actiontranslr()
    {
    	exit('dcm');
    	$libertyAPI = new LibertAPIWrapper();
    	
   		$response =$libertyAPI->sendmoney($_POST["lr_account"],'usd',$_POST['amount'],'false','service',"","chuyen tien tu vietlode");
		$withdraw = Withdraw::model()->find('serialno = :serialno', array(':serialno' => $_POST["serialno"]));
		$withdraw->batch=$response->Batch;
		$withdraw->send_date=$response->Date;
		$withdraw->send_by=$response->Payer;
		$withdraw->status=1;
		if ($withdraw->update())
			echo $withdraw->batch;
		else echo 'eo ghi dc';
    }
    
    public function actiontest()
    {
    	/*exit; code update lr_money cho  user
    	for ($i=2;$i<=2532;$i++)
    	{
    		$dm=Yii::app()->db->createcommand("select sum(lr_amount) from
    				ld_deposit_history where user_id=".$i)->queryScalar();
    		$wm=Yii::app()->db->createcommand("select sum(money) from
    				ld_withdraw where user_id=".$i)->queryScalar();    		
    		$m=round($dm-$wm,1,PHP_ROUND_HALF_DOWN);
    		echo $m.'<br/>';
    		Yii::app()->db->createcommand("UPDATE ld_user set lr_money=".$m." where
    				user_id=".$i)->query();
    	}
    	exit;*/
    	/*echo 'aaa'; // code them user bot
    	foreach ($list as $rec){
    		
    		$sql="INSERT INTO ld_user(user_name,bot) VALUES('".$rec."',1)";
    		echo $sql.'<br/>';
    		Yii::app()->db->createcommand($sql)->query();
    	}*/
    
    	$bots=Yii::app()->db->createCommand('select * from ld_user where bot=1')
    	->queryAll();
    	
    	$numofbots=Yii::app()->db->createCommand('select count(*) from ld_user where bot=1')
    	->queryScalar();
    	
    	/*for ($i=0;$i<$numofbots;$i++) code sua ten 
    	{
    		$tmp=$bots[$i]['user_name'];
    	
    	$newname=preg_replace('/[^a-zA-Z0-9*@]/i', '_', $bots[$i]['user_name']);
    	$bots[$i]['user_name']=$newname;
    	
    	if ($tmp<>$newname){
Yii::app()->db->createCommand("update ld_user set user_name='".$newname."' where user_id=".$bots[$i]['user_id'])->query();
    	echo $tmp.'======='.$newname.'<br/>';
    	}
    	//echo '<br/>';
    	}*/
    	
    	/*
    	 * code them withdraw
    	 */
    	/*
    	$extratime=300;
    	echo 'num of bot la : '.$numofbots.'<br/>';
    	
    	for ($d=400	;$d>-1;$d--)
    	{    	
    		echo 'd : '.$d.'<br/>';
    		$s=86400*$d;
    		$time=$s+86400;
    		   echo  date('Y-m-d H:i:s',strtotime("+14 hours -".$time." seconds")).'<br/>';	
    		   	
    		$sql="select a.user_id,sum(if (isnull(b.lr_amount),0,b.lr_amount)) - 
sum(if (isnull(c.money),0,c.money)) as remain from
ld_user a left join ld_deposit_history b on a.user_id=b.user_id left join
ld_withdraw c on a.user_id=c.user_id 
where 
(b.deposit_date <'".date('Y-m-d H:i:s',strtotime("+14 hours -".$time." seconds"))."' or b.deposit_date is null)
and 
(c.send_date<'".date('Y-m-d H:i:s',strtotime("+14 hours -".$time." seconds"))."' or c.send_date is null)
group by a.user_id
limit 0,50000 ";
    		
    		
    		$sql="select user_id,dm-wm as remain
from
(
    		
    		select t1.user_id,t1.dm,sum(if (isnull(c.money),0,c.money)) as wm from 
    (select a.user_id,sum(if (isnull(b.lr_amount),0,b.lr_amount)) as dm
    from ld_user a left join ld_deposit_history b on a.user_id=b.user_id
    where (b.deposit_date <'".date('Y-m-d H:i:s',strtotime("+14 hours -".$time." seconds"))."
    ' or b.deposit_date is null)
    group by a.user_id) as t1 
                        left join 
        ld_withdraw c on t1.user_id=c.user_id 
        where
            c.send_date<'".date('Y-m-d H:i:s',strtotime("+14 hours -".$time." seconds"))."' or c.send_date is null 
    group by t1.user_id limit 0,50000) as mtbl";
    		
    		echo $sql;
			$alluser=Yii::app()->db->createcommand($sql)->queryall(); 
			//var_dump($alluser);   	
			$number = round(count($alluser)/40,0,PHP_ROUND_HALF_DOWN);
			echo '<br/>so la : '.$number.'<br/>';
			$numrut=-1;
			foreach ($alluser as $u)
			{
				$xx=mt_rand(0,160);
				
				if (($xx<4)&&($numrut<$number-1)&&($u['remain']>2)) {
					echo 'so tien : '.$u['remain'].'<br/>';
					$numrut++;
					$timerut=mt_rand($time-86400/$number*($numrut+1),$time-86400/$number*$numrut);					
				//	echo 'rut tien '.date('Y-m-d H:i:s',strtotime("+14 hours -".$timerut." seconds"));
					//echo '---'.$u['user_id'].' -- '.(mt_rand(10,$u['remain']*10)/10).'<br/>';
					$sql="INSERT INTO ld_withdraw(user_id,money,currency,status,send_date)
					VALUES(".$u['user_id'].",".(mt_rand(10,$u['remain']*10)/20).",'LRUSD',1,
					'".date('Y-m-d H:i:s',strtotime("+14 hours -".$timerut." seconds"))."')";
					echo $sql.'<br/>';
					Yii::app()->db->createcommand($sql)->query();
					
					
				}
				
			}

    	}*/
    	/*
    	 for ($d=0;$d>-1;$d--){
    		
    		$s=86400*$d;
    		$time=$s+86400;
    		for ($f=0;$f<40;$f++)
    		{
    			$randid=mt_rand(0,$numofbots-1);
    			$exts=mt_rand(0,($time-$s)/40-$f);
    			$time-=$exts;
    			echo date('Y-m-d H:i:s',strtotime("+14 hours -".$time." seconds")).'<br/>';
    			$money=mt_rand(10,20)/2+mt_rand(0,1)*mt_rand(1,40)+mt_rand(0,1)*mt_rand(0,1)
    			*mt_rand(10,100)+mt_rand(0,1)*mt_rand(0,1)*mt_rand(0,1)*mt_rand(1,300);
    			//echo date('Y-m-d H:i:s',strtotime("+14 hours -".$time." seconds"))
    			//.'--'.
    			//$bots[$randid]['user_name']
    			//.'--'.
    			$sql="INSERT INTO ld_deposit_history(user_id,deposit_date,lr_amount,lr_currency)
    			VALUES(".$bots[$randid]['user_id'].",'
    			".date('Y-m-d H:i:s',strtotime("+14 hours -".$time." seconds"))."',
    			".$money.",'LRUSD')";
    			Yii::app()->db->createcommand($sql)->query();
    			$money.'<br/>';
    			$bot=User::model()->find('user_id=:user_id',array(':user_id'=>$bots[$randid]['user_id']));
    			$bot->lr_money+=$money;
    			if ($bot->save())
    				echo 'tang tien cho user'.$bot->user_name.'<br/>';
    			else
    				echo '<b>ko save dc </b><br/>';
    			
  
    		}
    		echo '**************************************************************<br/>';
    		
    		
    	}*/
			echo '<hr/>';

    }
        //
        
    public function actionkhan()
    {
    	$sql="SELECT x3dot5 from ld_ketquaxoso where date='".
    	date('Y-m-d',strtotime('+14 hours'))."'";
    	//echo $sql.'<br/>';
    	$ketqua=Yii::app()->db->createcommand($sql)->queryScalar(); 
    	//echo 'ket qua la : '.$ketqua;  
    	print_r($ketqua);
    	if ($ketqua==null)
    	{
    		echo 'ko co ket qua';
    		exit;
    	}
    	for ($i=0;$i<100;$i++)
    	{
    		$dauso = Lokhan::model()->find('value=:value',array(':value'=>$i));
    		echo $dauso->value.'----'.$dauso->days."<br/>";
    		$str=strval($dauso->value);
    		if ($dauso->value<10)
    			$str='0'.$str;
    		if (!strpos($ketqua,$str)){
    			echo 'khong co trong danh sach <br/>';
    			$dauso->days+=1;
    			if ($dauso->days>$dauso->max_khan){
    				echo 'tang max_khan <br/>';; 
    				$dauso->max_khan=$dauso->days; 
    			}   			
    		}
    		else{
    			$dauso->days=0;
    		}
    		$dauso->save();
    	}
    	/*
 
    	
    	$result=array();
    	$sum=0;
    	for ($num=0;$num<=99;$num++)
    	{
    		$str=strval($num);
    		if ($num<10) $str='0'.$str;
    		for ($day=0;$day<100;$day++){
    			$date= date('Y-m-d',strtotime("+14 hours - ".$day." days"));
    			$sql="SELECT x3dot5 from ld_ketquaxoso where date='".$date."'"; 
    			//echo $sql.'<br/>';
    			$ketqua=Yii::app()->db->createcommand($sql)->queryScalar();   	
    			//echo $ketqua.'<br/>';		
    			if (strpos($ketqua, $str)>0){
    				echo 'so '.$str.' ra gan nhat la cach day '.$day.'<br/>';
    				if ($day>1)
    				$sum+=$day;
    				$result[$str]=$day;
Yii::app()->db->createcommand("UPDATE ld_lokhan set days=".$day." where value=".$num)->query();    				
    				break;
    			}
    				
    		}
    	
    	}
    	echo $sum;*/
    }
    public function actionWithDraw()
    {
    	
		$withdraws= Withdraw::getWithdrawNotDone();
    	
    	$this->render('backend/admin/withdraw', array('withdraws'=>$withdraws)); 	
    }

    //Game bomb
    public function actionBomb()
    {
        $data = array();
        if (isset($_POST['btn_changerule']))
        {
            //save data
            Yii::app()->db->createCommand()
                    ->update('ld_setting', array('value' => $_POST['textarea_id']), 'variable="bomb_rule_text"');
        }

        //load data
        $rule = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_setting')
                ->where('variable=:v', array(':v' => 'bomb_rule_text'))
                ->queryRow();
        $data['rule'] = $rule;
        $this->render('backend/admin/bomb_setting', $data);
    }

    //Black or White
    public function actionBlackorWhite()
    {
        $data = array();
        if (isset($_POST['btn_changerule']))
        {
            //save data
            Yii::app()->db->createCommand()
                    ->update('ld_setting', array('value' => $_POST['textarea_id']), 'variable="blackorwhite_rule_text"');
        }

        //load data
        $rule = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_setting')
                ->where('variable=:v', array(':v' => 'blackorwhite_rule_text'))
                ->queryRow();
        $data['rule'] = $rule;
        $this->render('backend/admin/blackorwhite_setting', $data);
    }

    //Lucky train
    public function actionLuckytrain()
    {
        $data = array();
        if (isset($_POST['btn_changerule']))
        {
            //save data
            Yii::app()->db->createCommand()
                    ->update('ld_setting', array('value' => $_POST['textarea_id']), 'variable="luckytrain_rule_text"');
        }

        //load data
        $rule = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_setting')
                ->where('variable=:v', array(':v' => 'luckytrain_rule_text'))
                ->queryRow();
        $data['rule'] = $rule;
        $this->render('backend/admin/luckytrain_setting', $data);
    }

    //List news
    public function actionNews()
    {
        $data = array();
        //load data
        $list_news = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_news')
                ->queryAll();
        $data['list_news'] = $list_news;
        $this->render('backend/admin/infonews', $data);
    }

    //News detail
    public function actionNewsdetail()
    {
        $data = array();

        if (isset($_GET['id']))
        {
        	
            $id = $_GET['id'];
           
            //load data
            $news_detail = Yii::app()->db->createCommand()
                    ->select('*')
                    ->from('ld_news')
                    ->where('id=:id', array(':id' => $id))
                    ->queryRow();
           
            //get data
        }
        else
        {
            $this->redirect(Yii::app()->request->baseUrl.'/backend/admin/news');
        }

        //save
        if (isset($_POST['btn_changerule']))
        {
            $news = array();
            $id = $_GET['id'];
            $news['title'] = $_POST['txtTitle'];
            $news['content'] = $_POST['textarea_id'];
            Yii::app()->db->createCommand()
                    ->update('ld_news', $news, 'id='.$id);
            $this->redirect(Yii::app()->request->baseUrl.'/backend/admin/news');
        }

        $data['news_detail'] = $news_detail;
        $this->render('backend/admin/newsdetail', $data);
    }

    //user
    public function actionUsers()
    {
    	
        $data = array();
        $user = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_user')
                ->where('lr_acc is not null')
                
                ->queryAll();
        $data['users'] = $user;
        
        $this->render('backend/admin/user', $data);
    }

    //user
    public function actionEditusers()
    {
        //http://localhost/lode/index.php/backend/admin/Editusers?id=1
        if (isset($_GET['id']))
        {
        	
            $data = array();
            $id = $_GET['id'];
            
            if (isset($_POST['btnban']))
            {
            	
                $edituser = array();
                $edituser['active'] = 2;
                echo 'lenh ban : ';
                var_dump($edituser);
                Yii::app()->db->createCommand()
                        ->update('ld_user', $edituser, 'user_id='.$id);
            }

            if (isset($_POST['btnunban']))
            {
                $edituser = array();
                $edituser['active'] = 1;
                Yii::app()->db->createCommand()
                        ->update('ld_user', $edituser, 'user_id='.$id);
            }

            $user = Yii::app()->db->createCommand()
                    ->select('*')
                    ->from('ld_user')
                    ->where('user_id=:id', array(':id' => $id))
                    ->queryRow();
            $data['user'] = $user;
           
            $this->render('backend/admin/edituser', $data);
        }
        else
        {
            $this->redirect(Yii::app()->request->baseUrl.'/backend/admin/users');
        }
    }

    public function actionLayKetQuaXoSo()
    {
        $today = (isset($_POST['date']) && $_POST['date'] !== '') ? $_POST['date'] : '';
        
        if($today !== '')
        {
            $tmp = explode('-', $today);
            $today = join('/', array_reverse($tmp));
        }
        else
        {
            $today = date('d/m/Y');
        }
        echo '<strong>Káº¿t quáº£ xá»• sá»‘ ngÃ y: '.$today.'</strong>';
        //die;
        /*
          // Initialize the curl object
          $curl = curl_init();

          curl_setopt($curl, CURLOPT_URL, "http://www.xosothudo.com.vn/jquery/?option=com_main");
          curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);

          $data = array(
          'results_date' => $today
          );

          curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
          curl_setopt($curl, CURLOPT_POST, true);
          curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

          $response = curl_exec($curl);
          curl_close($curl);
         */

        $postdata = http_build_query(
                array(
                    'results_date' => $today,
                )
        );

        $opts = array('http' =>
            array(
                'method' => 'POST',
                'header' => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );

        $context = stream_context_create($opts);

        $response = file_get_contents('http://www.xosothudo.com.vn/jquery/?option=com_main', false, $context);

        $post = strrpos($response, "<table");

        if ($post)
        {
            $response = substr($response, $post);
            preg_match_all('/(<td>|<td style=(.*?)>)(.*?)<\/td>/', $response, $matches);
            $this->renderPartial('backend/admin/ketquaxoso', array('ketqua' => $matches[3]));
        }
        else
        {
            echo 'KhÃ´ng cÃ³ káº¿t quáº£';
        }
    }

    public function actionLoDe()
    {
    	$listnguoichoichuatra = LoDe::layDanhSachNguoiChoiChuaDuocTra();
    	$this->render('backend/admin/tratienlode',array('list'=>$listnguoichoichuatra));

    }

    public function actionNhapKetQuaLoDe()
    {
        $x80 = isset($_POST['x80']) ? $_POST['x80'] : '';
        $x8 = isset($_POST['x8']) ? $_POST['x8'] : '';
        $x3dot5 = isset($_POST['x3dot5']) ? $_POST['x3dot5'] : '';

        $today = (isset($_POST['date']) && $_POST['date'] !== '') ? $_POST['date'] : $today = date('Y-m-d');
        
        
        $ketquaxs = Ketquaxoso::model()->find('date= :date', array(':date' => $today));

        if ($ketquaxs)
        {
            $ketquaxs->x80 = json_encode(explode('-', $x80));
            $ketquaxs->x8 = json_encode(explode('-', $x8));
            $x3dot5Arr = explode('-', $x3dot5);
            sort($x3dot5Arr);
            $ketquaxs->x3dot5 = json_encode($x3dot5Arr);
            $ketquaxs->date = $today;
            $ketquaxs->last_update = date('Y-m-d H:i:s');
            if ($ketquaxs->update())
            {
                echo 'thÃ nh cÃ´ng';
            }
        }
        else
        {
            $ketquaxs = new Ketquaxoso();
            $ketquaxs->x80 = json_encode(explode('-', $x80));
            $ketquaxs->x8 = json_encode(explode('-', $x8));
            $x3dot5Arr = explode('-', $x3dot5);
            sort($x3dot5Arr);
            $ketquaxs->x3dot5 = json_encode($x3dot5Arr);
            $ketquaxs->date = $today;
            $ketquaxs->last_update = date('Y-m-d H:i:s');

            if ($ketquaxs->save())
            {
                echo 'thÃ nh cÃ´ng';
            }
        }
    }

    public function actionLayDuLieuLoDe()
    {
        $ketquaxs = Ketquaxoso::model()->findBySql("SELECT DATE_FORMAT(a.date,'%d/%m/%Y') as date, a.x80, a.x8, a.x3dot5 FROM ld_ketquaxoso a ORDER BY a.date DESC");
        $this->renderPartial('backend/admin/ketqua_xoso', array('model' => $ketquaxs));
    }

    public function actionLayKetQuaXoSoTuDong()
    {
        $today = date('d/m/Y',strtotime("-24 hours"));
        $today = date('d/m/Y',strtotime("+14 hours"));
echo $today;
       
        /*
          // Initialize the curl object
          $curl = curl_init();

          curl_setopt($curl, CURLOPT_URL, "http://www.xosothudo.com.vn/jquery/?option=com_main");
          curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);

          $data = array(
          'results_date' => $today
          );

          curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
          curl_setopt($curl, CURLOPT_POST, true);
          curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

          $response = curl_exec($curl);
          curl_close($curl);
         */

        $postdata = http_build_query(
                array(
                    'results_date' => $today,
                )
        );

        $opts = array('http' =>
            array(
                'method' => 'POST',
                'header' => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );

        $context = stream_context_create($opts);

        $response = file_get_contents('http://www.xosothudo.com.vn/jquery/?option=com_main', false, $context);

        $post = strrpos($response, "<table");

        if ($post)
        {
            $response = substr($response, $post);
            preg_match_all('/(<td>|<td style=(.*?)>)(.*?)<\/td>/', $response, $matches);
            $this->renderPartial('backend/admin/ketquaxoso', array('ketqua' => $matches[3]));

            // lÆ°u DB
            //var_dump($matches[3]);
            $x80 = substr($matches[3][0], strlen($matches[3][0]) - 2);
            $arrX80 = array($x80);

            $arrX8 = str_split($x80, 1);

            $arrX3dot5 = explode('-', preg_replace('/\s+/', '', join('-', $matches[3])));
            for ($i = 0; $i < count($arrX3dot5); $i++)
            {
                $arrX3dot5[$i] = substr($arrX3dot5[$i], strlen($arrX3dot5[$i]) - 2);
            }
            sort($arrX3dot5);

            $today = date('Y-m-d');
            ;
            $ketquaxs = Ketquaxoso::model()->find('date= :date', array(':date' => $today));

            if ($ketquaxs)
            {
                $ketquaxs->x80 = json_encode($arrX80);
                $ketquaxs->x8 = json_encode($arrX8);
                $ketquaxs->x3dot5 = json_encode($arrX3dot5);
                $ketquaxs->date = $today;
                $ketquaxs->last_update = date('Y-m-d H:i:s');

                if ($ketquaxs->update())
                {
                    echo 'thÃ nh cÃ´ng';
                }
            }
            else
            {
                $ketquaxs = new Ketquaxoso();
                $ketquaxs->x80 = json_encode($arrX80);
                $ketquaxs->x8 = json_encode($arrX8);
                $ketquaxs->x3dot5 = json_encode($arrX3dot5);
                $ketquaxs->date = $today;
                $ketquaxs->last_update = date('Y-m-d H:i:s');
                if ($ketquaxs->save())
                {
                    echo 'thÃ nh cÃ´ng';
                }
            }
            $this->actionThongKeDanhSachThangGameLoDe();
        }
        else
        {
            echo 'KhÃ´ng cÃ³ káº¿t quáº£';
        }
    }

    public function actionThongKeDanhSachThangGameLoDe()
    {
    	$this->actionkhan();
        $ketquaHomNay = Ketquaxoso::layKetQuaXoSoHomNay();
        
        if ($ketquaHomNay)
        {
            $danhsachChoiHomNay = LoDe::layDanhSachLuotChoiHomNay();
            foreach ($danhsachChoiHomNay as $luotChoi)
            {
            	
                $game = LoDeFactory::createGameLoDe($luotChoi->lode_type);
                $game->setChoices(json_decode($luotChoi->choices));
                $game->setBet($luotChoi->bet);
				$user = User::model()->find('user_id = :user_id',array(':user_id'=>$luotChoi->player_id));
				
                $luotChoi->win_money = $game->calculateWinMoney($ketquaHomNay);
                $user->lr_money+=$luotChoi->win_money;
                echo $luotChoi->player_id;
                echo 'con tien'.$luotChoi->win_money;;
                if ($user->save())
                {
                	if ($luotChoi->win_money>0) 
                	{
                		$win = array();
                		$win['content'] = date("d-m H:i:s",strtotime("+14 hours")).'  -- <b>' .$user->user_name. '</b> trúng lô đề và đã kiếm được $' . $luotChoi->win_money;
                		$win['status'] = 1;                		
                		 Yii::app()->db->createCommand()->insert('ld_play_logs', $win);
                	}                	
                	$luotChoi->pay_status=1;
                }
                $luotChoi->save();               
                
            }
        }
    }

}
